<template>
	<view class="page">
		<view class="head">
			<view class="head1">
				<text class="iconfont icon-fenxiang1"  @click="goBack"></text>
				
				
			</view>
		</view>
		<view class="main">
			<!-- 搜索 -->
				<view class="search-head">
				  <view class="search">
					
						<input  class="search-input" confirm-type="search" v-model="keyword" placeholder="搜索商品" @confirm="onSearch">
				  </view>
				 
				</view>
			
				<!-- 搜索历史 -->
				<view class="search-record">
				  <view class="search-title">
				    <view class="title">历史记录</view>
				    <view class="right">
				      <view class="iconfont1" @click="toggleRecordList">
				        <view>{{ showRecords ? '收起' : '展开' }}</view>
				        <view class="iconfont icon-xiala"></view>
				      </view>
				      <view class="iconfont icon-laji" @click="clearAllRecords"></view>
				    </view>
				  </view>
				  
				  <!-- 展开/折叠功能：通过 showRecords 控制历史记录的显示 -->
				  <view class="record-list" v-show="showRecords">
				    <view class="list" v-for="(item, index) in SearchRecordArr" :key="index">
				      <text>{{ item }}</text>
				      <!-- 删除单个历史记录 -->
				      <view class="iconfont icon-del" @click="deleteRecord(index)"></view>
				    </view>
				  </view>
				</view>

				
			
		</view>
		</view>
</template>

<script>
	import uSearch from '@/uni_modules/uview-ui/components/u-search/u-search';

	export default {
		data() {
			return {
				 showRecords: true,
				SearchRecordArr: [],
				keyword: '',
			};
		},
		onLoad() {
			if(uni.getStorageSync('SearchRecordArr')){
				this.SearchRecordArr = JSON.parse(uni.getStorageSync('SearchRecordArr'));
			}
		},
		methods:{
			/**
			 * 返回点击
			 */
			goBack(){
						  uni.navigateBack(-1)
			},
			 toggleRecordList() {
			      this.showRecords = !this.showRecords;
			    },
			    // 删除某个历史记录项
			    deleteRecord(index) {
			      this.SearchRecordArr.splice(index, 1); // 删除对应项
			    },
			    // 清空所有历史记录
			    clearAllRecords() {
			      this.SearchRecordArr = []; // 清空数组
			    },
			/**
			 * 搜索点击
			 */
			onSearch(){
				 console.log('按下完成触发')
				if(!this.keyword){
					uni.showToast({
						title:'请输入搜索内容',
						icon:'none',
					})
					return;
				}
				for (var i = 0; i < this.SearchRecordArr.length; i++) {
					if (this.SearchRecordArr[i] == this.keyword) {
						this.SearchRecordArr.splice(i, 1);
					}
				}
				this.SearchRecordArr.unshift(this.keyword);
				uni.setStorageSync('SearchRecordArr', JSON.stringify(this.SearchRecordArr));
				uni.navigateTo({
					url: '/pages/SearchGoodsList/SearchGoodsList?keyword=' + encodeURIComponent(this.keyword),
				})
			},
			/**
			 * 记录点击
			 */
			onRecord(val){
				uni.navigateTo({
					url: '/pages/SearchGoodsList/SearchGoodsList?keyword=' + encodeURIComponent(val),
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import 'search.scss';
</style>
